<template>
    <div class="homeworkList">
        <div class="homework" :class="{ 'selected': isSelected(homework) }"
        v-for="homework in homeworkList" :key="homework.publishId" @click="itemClick(homework)">
            <span class="homeworkContent">
                <span class="iconfont" :class="{ 'icon-likesprogrampinggu' : homework.publishType == 'Exam', 'icon-likesprogramtianxie' : homework.publishType == 'Test' }"></span>
                <span class="homeworkTitle">{{ homework.homeworkInfo?.homeworkName }}</span>
            </span>
            <div class="homeworkTime">
                {{ homework.publishDate }}
            </div>
            <div class="homeworkStatus" v-if="homework.status >= 0">
                <div class="lable tips" v-if="homework.status == 0 && getRemainTime(homework.endTime) >  0">
                    未完成
                </div>
                <div class="surplusTime" :class="{
                    'tips': (getRemainTime(homework.endTime) <= 3600 && homework.status == 0)
                }" v-if="getRemainTime(homework.endTime) > 0">
                    剩余时间：{{ formatTime(getRemainTime(homework.endTime)) }}
                </div>
                <div class="lable complete" v-else-if="homework.status == 1">
                    待批阅
                </div>
                <div class="lable complete" v-else-if="homework.status == 2">
                    AI代批阅
                </div>
                <div class="lable" :class="{
                    'warning': homework.score < 60, 'tips': (homework.score >= 60 && homework.score < 85),
                    'complete': homework.score >= 85 }" v-else-if="homework.status == 3">
                    <span class="score">{{ homework.score }}</span><span>分</span>
                </div>
                <div class="lable warning" v-if="homework.status == 0 && getRemainTime(homework.endTime) <= 0">
                    已过期
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { convertHomeworkToPublish, Homework, isHomework, PublishHomework } from '@/types/Course';
import { defineComponent, watch, ref } from 'vue';
import { useRoute } from 'vue-router';

export default defineComponent({
    name: 'homeworkList',
});
</script>

<script setup lang="ts">
    // 定义props
    const props = withDefaults(defineProps<{
        modelValue: PublishHomework[] | Homework[];
        selectHomeworkId?: number | null;
        filter?: number;
    }>(), {
        modelValue: ()=>[],
        selectHomeworkId: null,
        filter: 0
    });

    const route = useRoute();
    const courseId = ref(0); // 获取 课程Id 参数
    // 作业列表
    const homeworkList = ref<PublishHomework[]>(null);
    const selectedHomework = ref<PublishHomework>(null);

    // 注册事件
    const emits = defineEmits(['update:modelValue', 'update:selectHomeworkId', 'itemClick']);

    // 点击列表项
    const itemClick = (item: PublishHomework) => {
        if(props.selectHomeworkId == null)
        {
            if(selectedHomework.value != null 
            && selectedHomework.value.publishId == item.publishId)
            selectedHomework.value = null;
            else selectedHomework.value = item;
        }
        emits('itemClick', item);
    };

    // 是否选择
    const isSelected = (item: PublishHomework) => {
        if (selectedHomework.value === null || selectedHomework.value === undefined
            || item === null || item === undefined
        ) {
            return false;
        }
        return item.publishId === selectedHomework.value.publishId;
    };

    // 剩余时间格式化函数
    const formatTime = (totalMilliseconds: number | null): string => {
        if (totalMilliseconds === null || totalMilliseconds <= 0) {
            return "0秒";
        }

        const totalSeconds = Math.floor(totalMilliseconds / 1000);
        const days = Math.floor(totalSeconds / 86400);
        const hours = Math.floor((totalSeconds % 86400) / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const seconds = totalSeconds % 60;

        if (days > 0) {
            return `${days}天${hours}小时`;
        }
        if (hours > 0) {
            return `${hours}小时${minutes}分钟`;
        }
        if (minutes > 0) {
            return `${minutes}分钟${seconds}秒`;
        }
        return `${seconds}秒`;
    };

    // 计算剩余时间（返回毫秒数）
    const getRemainTime = (endTime: string): number => {
        const now = new Date().getTime();
        const end = new Date(endTime).getTime();
        return Math.max(0, end - now); // 确保不会返回负数
    };

    // 参数转换函数（确保字符串转换为数字）
    const parseSafeInt = (value: string | string[] | undefined): number | undefined => {
        if (typeof value === 'string') {
            const num = parseInt(value, 10);
            return isNaN(num) ? undefined : num;
        }
        return undefined;
    };
    watch(() => ({
        modelValueParam: props.modelValue,
        selectHomeworkIdParam: props.selectHomeworkId,
        filterParam: props.filter,
        chourseIdParam: route.params.courseId
    }), async ({modelValueParam, selectHomeworkIdParam, filterParam, chourseIdParam}) => {
        if(modelValueParam)
        {
            // 判断modelValueParam类型是Homework[]还是PublishHomework[]
            if(!isHomework(modelValueParam[0])) {
                homeworkList.value = modelValueParam as PublishHomework[];
            } else {
                homeworkList.value = (modelValueParam).map(item => {
                    return convertHomeworkToPublish(item);
                }) as PublishHomework[];
            }
        }
        
        switch(filterParam) {
            case 0: // 全部
                break;
            case 1: // 未提交
                homeworkList.value = homeworkList.value.filter(item => {
                    return item.status === filterParam - 1;
                });
                break
            case 2: // 已提交
                homeworkList.value = homeworkList.value.filter(item => {
                    return item.status >= filterParam - 1;
                });
                break;
        }

        // 处理选中作业
        if(homeworkList.value && homeworkList.value.length > 0 && selectHomeworkIdParam)
        {
            const homework = homeworkList.value.find(h => h.publishId === selectHomeworkIdParam);
            if(homework) selectedHomework.value = homework;
            else selectedHomework.value = null;
        }
        
        if(chourseIdParam) courseId.value = parseSafeInt(chourseIdParam);
    },
    { immediate: true });
</script>

<style src="@/assets/icons/iconfont.css" scoped></style>

<style scoped>
/* 作业列表内容 */
.homeworkList {
    width: 100%;
    height: 100%;
    overflow-y: auto;
}
.homeworkList .homework {
    width: 100%;
    position: relative;
    transition: .3s all;
    border-bottom: 1px solid #e5e5e5;
    /* 单行 */
    white-space: nowrap;
    text-overflow: ellipsis;
}
.homeworkList .homework.selected,
.homeworkList .homework:hover {
    background-color: rgba(218, 218, 218, .2);
    border-bottom: 1px solid rgba(65, 185, 255, 1);

}
.homeworkList .homework.selected .iconfont,
.homeworkList .homework:hover .iconfont {
    color:rgba(65, 185, 255, 1);
}
.homeworkList .homework:active .iconfont {
    color:rgba(65, 185, 255, .8);
}
.homeworkList .homework:active {
    transition: .1s all;
    background-color: rgba(218, 218, 218, .1);
    border-bottom: 1px solid rgba(65, 185, 255, .5);
}
.homeworkList .homework .homeworkContent {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding-top: 5px;
}
.homeworkList .homework .iconfont {
    padding-left: 9px;
    font-size: 26px;
}
.homeworkList .homework .homeworkTitle {
    padding: 0px 9px;
    font-size: 14px;
    width: calc(100% - 32px);
}
.homeworkList .homework .homeworkTime {
    padding: 0px 10px;
    font-size: 12px;
    padding-bottom: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: rgba(0, 0, 0, .5);
}
.homeworkList .homework .homeworkStatus {
    padding: 0px 10px;
    font-size: 14px;
    right: 0px;
    top: 0px;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    position: absolute;
}
.homeworkList .homework .homeworkStatus .surplusTime {
    font-size: 12px;
    color: rgba(65, 185, 255, 1);
}

.homeworkList .homework .homeworkStatus .lable .score {
    padding: 0px 5px;
}

.homeworkList .homework .homeworkStatus .surplusTime.tips {
    color: rgba(255, 153, 0, 1);
}
.homeworkList .homework .homeworkStatus .lable.complete{
    color: rgba(65, 185, 255, 1);
}
.homeworkList .homework .homeworkStatus .lable.tips {
    color: rgba(255, 153, 0, 1);
}
.homeworkList .homework .homeworkStatus .lable.warning {
    color: rgba(255, 0, 0, 1);
}
</style>
